package com.ruoyi.app.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import javax.xml.bind.DatatypeConverter;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
 * @ClassName: PhotoUtils
 * @Author: chenJie
 * @Description:
 */
public class PhotoUtils {

    private static String URL = "https://www.baidu.com/";
    /**
     * 生成二维码的方法
     */
    public static String generateQRCodeBase64() {
        int width = 300;
        int height= 300;
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {

            // 生成二维码矩阵
            BitMatrix bitMatrix = qrCodeWriter.encode(URL, BarcodeFormat.QR_CODE, width, height);

            // 将矩阵转换为 BufferedImage
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            // 将 BufferedImage 转换为字节数组输出流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            javax.imageio.ImageIO.write(bufferedImage, "PNG", outputStream);

            // 将字节数组转换为 Base64 字符串
            byte[] imageBytes = outputStream.toByteArray();
            String result = "data:image/png;base64," + DatatypeConverter.printBase64Binary(imageBytes);
            return result;

        } catch (WriterException | IOException e) {
            System.err.println("生成二维码时发生错误: " + e.getMessage());
        }
        return null;
    }
}
